package initenv

import (
	"log"
	"os"
	"path/filepath"
	"scada"
	"strings"

	"github.com/astaxie/beego/logs"
)

//设置日志级别
func SetLogLevel(level string) {
	level = strings.ToLower(level)
	switch level {
	case "emergency":
		logs.SetLevel(logs.LevelEmergency)
	case "alert":
		logs.SetLevel(logs.LevelAlert)
	case "error":
		logs.SetLevel(logs.LevelError)
	case "warn", "warning":
		logs.SetLevel(logs.LevelWarn)
	case "info", "informational":
		logs.SetLevel(logs.LevelInfo)
	case "debug":
		logs.SetLevel(logs.LevelDebug)
	}
}

func Reset() {
	binaryPath, _ := filepath.Abs(os.Args[0])
	os.Chdir(filepath.Dir(binaryPath))
	os.Mkdir("logs", 0775)

	app := strings.TrimPrefix(binaryPath, filepath.Dir(binaryPath))
	app = strings.TrimRight(app, filepath.Ext(app))
	app = strings.TrimLeft(app, "/\\")

	logs.SetLogFuncCall(true)
	//logs.SetLogger(logs.AdapterConsole)

	const logPath = scada.LOG_DEFAUTL_PATH
	f, err := os.Stat(logPath)
	if err == nil && f.IsDir() {
		logs.SetLogger("file", `{"filename":"`+logPath+app+`.log"}`)
	} else {
		logs.SetLogger("file", `{"filename":"logs/`+app+`.log"}`)
	}

	log.SetFlags(log.Lshortfile | log.LstdFlags)
}
